package org.yn.auth.service.impl;

import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yn.auth.dto.LoginDTO;
import org.yn.auth.service.ILoginService;
import org.yn.base.until.LoginContext;
import org.yn.emp.domain.Employee;
import org.yn.emp.mapper.EmployeeMapper;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> login(LoginDTO user) {
        // 先判断user的账号和密码是否为空
        if (StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())){
            throw  new RuntimeException("请输入账号和密码");
        }

        //查询账号 的密码 来判断
        //没有查到账号
        Employee employee = employeeMapper.selectByName(user.getUsername());
    if (Objects.isNull(employee)){
        throw new RuntimeException("用户不存在");
    }

    // 判断密码
        if (!employee.getPassword().equals(user.getPassword())){
            throw new RuntimeException("密码错误");
        }

        //将user存入map
        //生成uuid 给全局loginmap 和 employee结合

        String uuid1 = UUID.randomUUID().toString();
        //方便测试现在将uuid写成固定的
        String uuid ="test";

        System.out.println("生成的uuid:"+uuid);
        LoginContext.loginMap.put(uuid,employee);

        //new一个hasmap 返回给前端
        //将employee的pwd和id设置为null（敏感信息
        employee.setPassword(null);
//        employee.setId(null);

//        返回的是”token“+UUID
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",uuid);
        map.put("user",employee);
        return map;
    }
}
